﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using WMS.BatchReceivings.Dto;
using WMS.OutboundDetailss.Dto;
using WMS.OutboundDetailss;
using WMS.Common;
using Volo.Abp.ObjectMapping;

namespace WMS.BatchReceivings
{
    public class BatchReceivingService : ApplicationService, IBatchReceivingService
    {
        private readonly IRepository<BatchReceiving, int> _repository;

        public BatchReceivingService(IRepository<BatchReceiving, int> repository)
        {
            _repository = repository;
        }

        public async Task<int> AddBatchReceiving(BatchReceivingDto batchReceivingDto)
        {
            var batchReceivingModel = batchReceivingDto.MapTo<BatchReceiving>();
            await _repository.InsertAsync(batchReceivingModel);
            return batchReceivingDto.Id;
        }

        public async Task<int> DeleteBatchReceiving(int id)
        {
            await _repository.DeleteAsync(id);
            return 1;
        }

        public async Task<BatchReceivingDto> GetBatchReceivingInfo(int id)
        {
            var entity = _repository.GetAsync(id).Result;
            var batchReceivingDto = ObjectMapper.Map<BatchReceiving, BatchReceivingDto>(entity);
            return batchReceivingDto;
        }

        public async Task<PagedResult> GetBatchReceivingList(string? createName, int page = 1, int limit = 10)
        {
            var predicate = PredicateBuilder.New<BatchReceiving>(true);
            if (!string.IsNullOrEmpty(createName))
            {
                predicate = predicate.And(m => m.CreateName.Contains(createName));
            }
            var dto = _repository.GetListAsync(predicate).Result;
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((decimal)(dto.Count == 0 ? 1 : dto.Count) / limit);
            result.PageSize = limit;
            result.CurrentPage = page;
            result.RowCount = dto.Count;
            result.Queryable = dto.Skip((page - 1) * limit).Take(limit).AsQueryable();
            return result;
        }

        public async Task<int> UpdateBatchReceiving(BatchReceivingDto batchReceivingDto)
        {
            BatchReceiving batchReceiving = batchReceivingDto.MapTo<BatchReceiving>();
            await _repository.UpdateAsync(batchReceiving);
            return batchReceiving.Id;
        }
    }
}
